<?php

function getPass($username, $pass)
{
    return sha1(md5(bin2hex(strrev(stripslashes(strtolower($username))))) . md5(stripslashes($pass)));
}
function getOldPass($username, $pass)
{
    return sha1(md5(bin2hex(strrev(stripslashes(strtolower($username))))) . md5(stripslashes(strtoupper($pass))));
}
function checkEmail($usr)
{
    global $DBobject;
    $sql = "SELECT * from tbl_admin WHERE admin_username = :user";
    $res = $DBobject->wrappedSqlGet($sql, array("user" => $usr));

    if (!empty($res)) {
        return 'true';
    }
    return 'false';
}

/**
 * Function accepts a string and appends a campaign string to the end.
 * @param string $string
 * @return mixed
 */
function AppendCampaignToString($string)
{
    $regex = '#(<a href=")([^"]*)("[^>]*?>)#i';
    return preg_replace_callback($regex, '_appendCampaignToString', $string);
}
function _AppendCampaignToString($match)
{
    $url = $match[2];
    if (strpos($url, '?') === false) {
        $url .= '?';
    }
    $url .= '&utm_source=email&utm_medium=email&utm_campaign=product_notify';
    return $match[1].$url.$match[3];
}

/**
 * Function accepts a string and appends google event tracking to file links.
 * @param string $string
 * @return mixed
 */
function AppendEventTrackingToString($string)
{
    $regex = '#(<a href=")([^"]*.doc)("[^>]*?>)#i';
    $string = preg_replace_callback($regex, '_appendEventTrackingToString', $string);
    $regex = '#(<a href=")([^"]*.docx)("[^>]*?>)#i';
    $string = preg_replace_callback($regex, '_appendEventTrackingToString', $string);
    $regex = '#(<a href=")([^"]*.txt)("[^>]*?>)#i';
    $string = preg_replace_callback($regex, '_appendEventTrackingToString', $string);
    $regex = '#(<a href=")([^"]*.cad)("[^>]*?>)#i';
    $string = preg_replace_callback($regex, '_appendEventTrackingToString', $string);
    $regex = '#(<a href=")([^"]*.xls)("[^>]*?>)#i';
    $string = preg_replace_callback($regex, '_appendEventTrackingToString', $string);
    $regex = '#(<a href=")([^"]*.xlsx)("[^>]*?>)#i';
    $string = preg_replace_callback($regex, '_appendEventTrackingToString', $string);
    $regex = '#(<a href=")([^"]*.pdf)("[^>]*?>)#i';
    $string = preg_replace_callback($regex, '_appendEventTrackingToString', $string);
    return $string;
}
function _AppendEventTrackingToString($match)
{
    $url = $match[2];
    if (strpos($url, '?') === false) {
        $com = array_reverse(explode('/', $url));
        $url .= "\" onClick=\"ga('send', { 'hitType': 'event','eventCategory': 'file','eventAction': 'click','eventLabel': '$com[0]','eventValue': 'download'});";
    }
    return $match[1].$url.$match[3];
}

function urlSafeString($str)
{
    $str = str_replace('&', 'and', $str);
    $str = preg_replace("/[\"\']/", "", $str);
    $str = str_replace(' ', '-', $str);
    $str = preg_replace('/[^A-Za-z0-9\-]/', '', $str);
    //$str = preg_replace("/[^\s^\d^\w]+/", "", $str);
    $str = strtolower($str);
    $str = preg_replace('/--+/', '-', $str);
    return $str;
}

function urlPrep($str)
{
    $str = trim($str, '/');
    return $str;
}

function isValidInetAddress($data, $strict = false)
{
    $regex = $strict?
      '/^([.0-9a-z_-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,4})$/i' :
       '/^([*+!.&#$�\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,4})$/i'
       ;
    if (preg_match($regex, trim($data), $matches)) {
        return true;
    } else {
        return false;
    }
}

function isValidPassword($data)
{
    $r1='/[A-Z]/';  //Uppercase
    $r2='/[a-z]/';  //lowercase
    $r3='/[!@#$%^&*()-_=+{};:,<.>]/';  // whatever you mean by 'special char'
    $r4='/[0-9]/';  //numbers

    $regex = '/[A-Z]/';
    if (preg_match_all($regex, trim($data), $matches)<1) {
        return false;
    }
    $regex = '/[a-z]/';
    if (preg_match_all($regex, trim($data), $matches)<1) {
        return false;
    }
    $regex='/[0-9]/';
    if (preg_match_all($regex, trim($data), $matches)<1) {
        return false;
    }
    if (strlen(trim($data))<8) {
        return false;
    }

    return true;
}

function isValidUsername($data)
{
    if (preg_match('/\W/', $data)) {
        return false;
    } else {
        return true;
    }
}

function parse_backtrace($raw)
{
    $output="Trace:<br/>";
    try {
        foreach ($raw as $entry) {
            $output.="<br/>File: ".$entry['file']." (Line: ".$entry['line'].")<br/>";
            $output.="Function: ".$entry['function']."<br/>";
            try {
                $output.="Args: ".implode(", ", $entry['args'])."<br/>";
            } catch (Exception $e) {
            }
        }
    } catch (Exception $e) {
    }
    return $output;
}

function formatBytes($size, $precision = 2)
{
    $base = log($size) / log(1024);
    $suffixes = array('', 'k', 'M', 'G', 'T');
    return round(pow(1024, $base - floor($base)), $precision) .' '. $suffixes[floor($base)];
}
/**
 * Checks if the string $haystack starts with the string $needle
 * @param string $haystack
 * @param string $needle
 * @return boolean
 */
function startsWith($haystack, $needle)
{
    $length = strlen($needle);
    return (strtolower(substr($haystack, 0, $length)) === strtolower($needle));
}
/**
 * Checks if the string $haystack ends with the string $needle
 * @param string $haystack
 * @param string $needle
 * @return boolean
 */
function endsWith($haystack, $needle)
{
    $length = strlen($needle);
    $start  = $length * -1; //negative
    return (strtolower(substr($haystack, $start)) === strtolower($needle));
}

/**
 * Generate random-alphanumeric-character string with a given number for its length.
 *
 * @param int $length
 * @return string
 */
function genRandomString($length = 5)
{
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $string = '';
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }
    return $string;
}
function logError($trace, $err, $sql = false)
{
    global  $CONFIG;
    date_default_timezone_set('Australia/Adelaide');
    $datetime = date('r');
    $msg = "$datetime<br/><br/>$err";
    if (!empty($sql)) {
        $msg .= "<br/>$sql<br/>";
    }
    $debug = (string)$CONFIG->attributes()->debug;
    if ($debug == 'true') {
        die("$msg<br/>$trace");
    } else {
        sendMail("readysteadygokids@bccgmail.com", $CONFIG->attributes->company_name.'-Website', 'noreply@website.com.au', 'Error', "$msg<br/>$trace");
        header('Location: /404');
        die();
    }
}

/**
 * 发送邮件 不包含附件
 * @param  [type]  $to        [description]
 * @param  [type]  $from      [description]
 * @param  [type]  $fromEmail [description]
 * @param  [type]  $subject   [description]
 * @param  [type]  $body      [description]
 * @param  string  $bcc       [description]
 * @param  integer $userId    [description]
 * @param  integer $adminId   [description]
 * @return [type]             [description]
 */
function sendMail($to, $from, $fromEmail, $subject, $body, $bcc = "", $userId = 0, $adminId = 0)
{
    global $DBobject,$CONFIG;
    include_once 'includes/classes/PHPMailerAutoload.php';
    $mailSent = 0;

    try {
        $verify = true;
        // $sql = "SELECT count(email_id) as cnt FROM tbl_email_queue WHERE email_sent = 1 AND email_modified BETWEEN DATE_SUB(NOW(), INTERVAL 60 MINUTE) AND NOW() ";
        // if ($resc = $DBobject->executeSQL($sql)) {
        //     $verify = ($resc[0]['cnt'] >= 480)? false : true;
        // }
        
        if (function_exists("PHPMailerAutoload") && $verify && !empty($CONFIG->smtp->host) && !empty($CONFIG->smtp->port) && !empty($CONFIG->smtp->username) && !empty($CONFIG->smtp->password)) {
            $sql = "SELECT email_id FROM tbl_email_queue WHERE email_ip = :ip AND email_created BETWEEN DATE_SUB(NOW(), INTERVAL 1 MINUTE) AND NOW() LIMIT 5";
            $params = array(
                ":ip"=>$_SERVER['REMOTE_ADDR']
            );
            $res = $DBobject->executeSQL($sql, $params);
            if (count($res) < 5 || !empty($_SESSION['user']['admin'])) {
                //$mailSent = SafeMail($to, $subject, $body, $headers);
                
                $mail = new PHPMailer;
                $mail->isSMTP();
                $mail->Timeout = 5;
                $mail->Host = (string)$CONFIG->smtp->host;
                $mail->Port = (string)$CONFIG->smtp->port;
                $mail->SMTPAuth = true;
                $mail->Username = (string)$CONFIG->smtp->username;
                $mail->Password = (string)$CONFIG->smtp->password;
                $mail->setFrom((string)$CONFIG->smtp->username, $from);
                $mail->addAddress($to);
                //$mail->addBCC("info@readysteadygokids.com.cn");
                if (!empty($bcc)) {
                    $bcc = explode(',', $bcc);
                    foreach ($bcc as $value) {
                        $mail->addBCC($value);
                    }
                }
                $mail->Subject = $subject;
                $mail->Body = $body;
                $mail->isHTML(true);
                if (!$mail->send()) {
                    //echo "Mailer Error: " . $mail->ErrorInfo;exit;
                    $mailSent = -2;
                } else {
                    $mailSent = 1;
                }
            } else {
                $mailSent= -1;
            }
        }
    } catch (Exception $e) {
    }
    
    try {
        $sql = "INSERT INTO tbl_email_queue (email_to, email_header, email_subject, email_content,email_ip,email_sent,email_user_id,email_admin_id,email_modified) VALUES 
	      (:to,:header,:subject,:content,:ip,:sent,:email_user_id,:email_admin_id,now())";
        $params = array(
            ":to"=>$to,
            ":header"=>$headers,
            ":subject"=>$subject,
            ":content"=>utf8_encode($body),
            ":ip"=>$_SERVER['REMOTE_ADDR'],
            ":sent"=>$mailSent,
            ":email_user_id"=>$userId,
            ":email_admin_id"=>$adminId
        );
        $DBobject->executeSQL($sql, $params);
        //return $DBobject->wrappedSqlIdentity();
    } catch (Exception $e) {
    }
    
    return ($mailSent==1);
}

/**
 * 发送邮件，包含附件
 * @param  [type]  $to             [description]
 * @param  [type]  $from           [description]
 * @param  [type]  $fromEmail      [description]
 * @param  [type]  $subject        [description]
 * @param  [type]  $body           [description]
 * @param  [type]  $bcc            [description]
 * @param  [type]  $attachmentFile [description]
 * @param  integer $userId         [description]
 * @param  integer $adminId        [description]
 * @return [type]                  [description]
 */
function sendAttachMail($to, $from, $fromEmail, $subject, $body, $bcc = "", $attachmentFile = "", $userId = 0, $adminId = 0)
{
    global $DBobject, $CONFIG;
    include_once 'includes/classes/PHPMailerAutoload.php';

    $mailSent = 0;
    try {
        if (function_exists("PHPMailerAutoload") && !empty($CONFIG->smtp->host) && !empty($CONFIG->smtp->port) && !empty($CONFIG->smtp->username) && !empty($CONFIG->smtp->password)) {
            $sql = "SELECT email_id FROM tbl_email_queue WHERE email_ip = :ip AND email_created BETWEEN DATE_SUB(NOW(), INTERVAL 1 MINUTE) AND NOW() LIMIT 5";
            $params = array(
                ":ip"=>$_SERVER['REMOTE_ADDR']
            );
            $res = $DBobject->executeSQL($sql, $params);
            if (count($res) < 5 || !empty($_SESSION['user']['admin'])) {
                /*$mail = new AttachmentMail($to, $subject, $from, $fromEmail);
            
                if (!empty($attachmentFile)) {
                    if (!is_array($attachmentFile)) {
                        $attachmentFile = array($attachmentFile);
                    }
                    foreach ($attachmentFile as $att) {
                        if (file_exists($att)) {
                            $mp1 = new Multipart($att);
                            $mail->addAttachment($mp1);
                        }
                    }
                }
            
                $mail->addBCC('readysteadygokids@gmail.com');
                if (!empty($bcc)) {
                    $mail->addBCC($bcc);
                }
            
                $mail->setHtml($body);
            
                $sql = "SELECT email_id FROM tbl_email_queue WHERE email_ip = :ip AND email_created BETWEEN DATE_SUB(NOW(), INTERVAL 1 MINUTE) AND NOW() LIMIT 5";
                $params = array(
                        ":ip"=>$_SERVER['REMOTE_ADDR']
                );
                $res = $DBobject->executeSQL($sql, $params);
                if (count($res) < 5  || !empty($_SESSION['user']['admin'])) {
                    $mailSent = $mail->send();
                } else {
                    $mailSent= -1;
                }
                */
                $mail = new PHPMailer;
                $mail->isSMTP();
                $mail->Timeout = 5;
                $mail->Host = (string)$CONFIG->smtp->host;
                $mail->Port = (string)$CONFIG->smtp->port;
                $mail->SMTPAuth = true;
                $mail->Username = (string)$CONFIG->smtp->username;
                $mail->Password = (string)$CONFIG->smtp->password;
                $mail->setFrom((string)$CONFIG->smtp->username, $from);
                $mail->addAddress($to);
                //$mail->addBCC("info@readysteadygokids.com.cn");
                if (!empty($bcc)) {
                    $bcc = explode(',', $bcc);
                    foreach ($bcc as $value) {
                        $mail->addBCC($value);
                    }
                }
                $mail->Subject = $subject;
                $mail->Body = $body;
                $mail->isHTML(true);
                if (!empty($attachmentFile)) {
                    if (!is_array($attachmentFile)) {
                        $attachmentFile = [$attachmentFile];
                    }
                    foreach ($attachmentFile as $att) {
                        if (file_exists($att)) {
                            $mail->addAttachment($att);
                        }
                    }
                }
                if (!$mail->send()) {
                    //echo "Mailer Error: " . $mail->ErrorInfo;exit;
                    $mailSent = -2;
                } else {
                    $mailSent = 1;
                }
            }
        }
    } catch (Exception $e) {
    }

    try {
        $headers = '';
        $sql = "INSERT INTO tbl_email_queue (email_to, email_header, email_subject, email_content,email_file,email_ip,email_sent,email_user_id,email_admin_id,email_modified) VALUES
          (:to,:header,:subject,:content,:file,:ip,:sent,:email_user_id,:email_admin_id,now())";
        $params = array(
                ":to"=>$to,
                ":header"=>$headers,
                ":subject"=>$subject,
                ":content"=>utf8_encode($body),
                ":ip"=>$_SERVER['REMOTE_ADDR'],
                ":file"=>json_encode($attachmentFile),
                ":sent"=>$mailSent,
            ":email_user_id"=>$userId,
            ":email_admin_id"=>$adminId
        );
        $DBobject->executeSQL($sql, $params);
        return $DBobject->wrappedSqlIdentity();
    } catch (Exception $e) {
    }

    return false;
}

/**
 * Create bulk emails in the database. It does NOT send them
 *
 * @param array $to_Array
 * @param string $from
 * @param string $fromEmail
 * @param string $subject
 * @param string $body
 * @return boolean
 */
function createBulkMail($to_Array, $from, $fromEmail, $subject, $body, $adminId = 0, $userKeyArr = array())
{
    global $DBobject;

    /* To send HTML mail, you can set the Content-type header. */
    $headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
    $headers .= "X-Priority: 3\r\n";
    $headers .= "X-Mailer: PHP". phpversion() ."\r\n";

    /* additional headers */
    $headers .= "Reply-To: ". $from . " <".$fromEmail.">\r\n";
    $headers .= "Return-Path: ". $from . " <".$fromEmail.">\r\n";
    $headers .= "From: ". $from . " <".$fromEmail.">\r\n";
    $headers .= "Bcc: readysteadygokids@gmail.com\r\n";
    
    try {
        foreach ($to_Array as $k => $to) {
            $sql = "INSERT INTO tbl_email_queue (email_to, email_header, email_subject, email_content,email_ip,email_sent,email_user_id,email_admin_id,email_modified) VALUES
		      (:to,:header,:subject,:content,:ip,:sent,:email_user_id,:email_admin_id, now())";
            $params = array(
                    ":to"=>$to,
                    ":header"=>$headers,
                    ":subject"=>$subject,
                    ":content"=>utf8_encode($body),
                    ":ip"=>$_SERVER['REMOTE_ADDR'],
                    ":sent"=>-2,
                ":email_user_id"=> (empty($userKeyArr[$k])?'0':$userKeyArr[$k]),
                ":email_admin_id"=>$adminId
            );
            $DBobject->executeSQL($sql, $params);
        }
        return true;
    } catch (Exception $e) {
    }
    return false;
}

/**
 * Send bulk emails in the queue. By default it is limited to 100 emails.
 *
 * @return boolean
 */
function sendBulkMail()
{
    global $DBobject;
    try {
        if (is_readable($_SERVER['DOCUMENT_ROOT'].'database/safemail.php')) {
            require_once 'database/safemail.php';
        }
    } catch (Exception $e) {
    }

    $cnt = 0;
    $_limit = 50;
    try {
        $verify = false;
        $sql = "SELECT count(email_id) as cnt FROM tbl_email_queue WHERE email_sent = 1 AND email_modified BETWEEN DATE_SUB(NOW(), INTERVAL 60 MINUTE) AND NOW() ";
        if ($resc = $DBobject->executeSQL($sql)) {
            if ($resc[0]['cnt'] >= 480) {
                $verify = false;
            } else {
                $verify = true;
                $max = 480 - $resc[0]['cnt'];
                $sendamount = intval($max/2);
                $_limit = ($sendamount >= $_limit)?$_limit: $sendamount;
            }
        }
        
        if (function_exists("SafeMail") && $verify) {
            $sql = "SELECT * FROM tbl_email_queue WHERE email_sent = '-2' OR email_sent = '0' ORDER BY email_sent = 0 DESC,email_created LIMIT $_limit";
            if ($res = $DBobject->executeSQL($sql)) {
                foreach ($res as $r) {
                    if (SafeMail($r['email_to'], $r['email_subject'], $r['email_content'], $r['email_header'])) {
                        $sql = "UPDATE tbl_email_queue SET email_sent = '1',email_modified = now() WHERE email_id = :email_id";
                        $DBobject->executeSQL($sql, array(":email_id"=>$r['email_id']));
                        $cnt++;
                    }
                }
            }
            return $cnt;
        }
    } catch (Exception $e) {
        die("Error: $e");
    }
    return false;
}

function sendMailV2($to, $from, $fromEmail, $subject, $body)
{
    global $DBobject;
    try {
        if (is_readable($_SERVER['DOCUMENT_ROOT'].'database/safemail.php')) {
            require_once 'database/safemail.php';
        }
    } catch (Exception $e) {
    }
    define("DEFCALLBACKMAIL", "{$fromEmail}");
    define("DEFCALLBACKNAME", "MedicAlert Foundation");
    $final_msg = preparehtmlmail($body);

    $mailSent = 0;
    try {
        if (function_exists("SafeMail")) {
            $sql = "SELECT email_id FROM tbl_email_queue WHERE email_ip = :ip AND email_created BETWEEN DATE_SUB(NOW(), INTERVAL 1 HOUR) AND NOW() LIMIT 5";
            $params = array(
              ":ip"=>$_SERVER['REMOTE_ADDR']
            );
            $res = $DBobject->executeSQL($sql, $params);
            if (count($res) < 5  || !empty($_SESSION['user']['admin'])) {
                  $mailSent = SafeMail($to, $subject, $final_msg['headers'], $final_msg['multipart']);
            } else {
                  $mailSent= -1;
            }
        }
    } catch (Exception $e) {
    }

    try {
        $sql = "INSERT INTO tbl_email_queue (email_to, email_header, email_subject, email_content,email_ip,email_sent) VALUES
	      (:to,:header,:subject,:content,:ip,:sent)";
        $params = array(
        ":to"=>$to,
        ":header"=>$final_msg['headers'],
        ":subject"=>$subject,
        ":content"=>$final_msg['multipart'],
                ":ip"=>$_SERVER['REMOTE_ADDR'],
        ":sent"=>$mailSent,
        );
        $DBobject->executeSQL($sql, $params);
    } catch (Exception $e) {
    }

    return $mailSent;
}

function preparehtmlmail($html)
{

    preg_match_all('~<img.*?src=.([\/.a-z0-9:_-]+).*?>~si', $html, $matches);
    $i = 0;
    $paths = array();

    foreach ($matches[1] as $img) {
        $img_old = $img;

        if (strpos($img, "http://") == false) {
            $uri = parse_url($img);
            $paths[$i]['path'] = $_SERVER['DOCUMENT_ROOT'].$uri['path'];
            $content_id = md5($img);
            $html = str_replace($img_old, 'cid:'.$content_id, $html);
            $paths[$i++]['cid'] = $content_id;
        }
    }

    $boundary = "--".md5(uniqid(time()));
    $headers .= "MIME-Version: 1.0\n";
    $headers .="Content-Type: multipart/mixed; boundary=\"$boundary\"\n";
    $headers .= "From: ".DEFCALLBACKNAME." <".DEFCALLBACKMAIL.">\n";
    $headers .= "Bcc: readysteadygokids@gmail.com\r\n";
    $multipart = '';
    $multipart .= "--$boundary\n";
    $kod = 'utf-8';
    $multipart .= "Content-Type: text/html; charset=$kod\n";
    $multipart .= "Content-Transfer-Encoding: Quot-Printed\n\n";
    $multipart .= "$html\n\n";

    foreach ($paths as $path) {
        if (file_exists($path['path'])) {
            $fp = fopen($path['path'], "r");
        }
        if (!$fp) {
            return false;
        }

        $imagetype = substr(strrchr($path['path'], '.'), 1);
        $file = fread($fp, filesize($path['path']));
        fclose($fp);

        $message_part = "";

        switch ($imagetype) {
            case 'png':
            case 'PNG':
                  $message_part .= "Content-Type: image/png";
                break;
            case 'jpg':
            case 'jpeg':
            case 'JPG':
            case 'JPEG':
                  $message_part .= "Content-Type: image/jpeg";
                break;
            case 'gif':
            case 'GIF':
                  $message_part .= "Content-Type: image/gif";
                break;
        }

        $message_part .= "; file_name = \"$path\"\n";
        $message_part .= 'Content-ID: <'.$path['cid'].">\n";
        $message_part .= "Content-Transfer-Encoding: base64\n";
        $message_part .= "Content-Disposition: inline; filename = \"".basename($path['path'])."\"\n\n";
        $message_part .= chunk_split(base64_encode($file))."\n";
        $multipart .= "--$boundary\n".$message_part."\n";
    }
    $multipart .= "--$boundary--\n";
    return array('multipart' => $multipart, 'headers' => $headers);
}

function clean($str)
{
    $type = strtolower(gettype($str));
    switch ($type) {
        case "array":
            foreach ($str as $key => $val) {
                $str[$key]= clean($val);
            }
            break;
        case "string":
        default:
            $str = unclean($str); //Unclean the value first to make sure that we are not double cleaning. This needs to be done because add slashes is an unsafe function. It can cause multiple slashes.
            $str = htmlspecialchars(trim($str), ENT_QUOTES, 'UTF-8', false);
            $str = str_replace("&lt;", "<", $str);
            $str = str_replace("&gt;", ">", $str);
            $str = str_replace("&nbsp;", " ", $str);
            $str = addslashes($str);
            break;
    }

    return $str;
}

function htmlclean($str)
{
    $type = strtolower(gettype($str));

    switch ($type) {
        case "string":
            $str = unclean($str);
            $str = strip_tags($str);
            $str = htmlspecialchars(trim($str), ENT_QUOTES, 'UTF-8', false);
            $str = addslashes($str);
            break;

        case "array":
            foreach ($str as $key => $val) {
                $str[$key] = htmlclean($val);
            }
            break;
        default:
            $str = unclean($str);
            $str = strip_tags($str);
            $str = htmlspecialchars(trim($str), ENT_QUOTES, 'UTF-8', false);
            $str = addslashes($str);
            break;
    }
    return $str;
}

function unclean($str)
{
    $type = strtolower(gettype($str));
    switch ($type) {
        case "array":
            foreach ($str as $key => $val) {
                $str[$key]= unclean($val);
            }
            break;
        case "string":
        default:
            $str = stripslashes($str);
            $str = str_replace('&nbsp;', ' ', $str);
            $str = html_entity_decode($str, ENT_QUOTES, 'UTF-8');
            break;
    }
    return $str;
}

/**
 * Get a specific token if not created then generate it
 *
 * @param string $name
 * @return string
 */
function getToken($name)
{
    if ($_SESSION[$name . "-token"] && !empty($_SESSION[$name . "-token"])) {
        $action = "get";
    } else {
        $_SESSION[$name . "-token"] = generatetoken();
        $action = "set";
    }
    /* try {
		global $DBobject;
		$params = array (
				":log_admin_id" => $_SESSION['user']['admin']["id"],
				":log_user_id" => $_SESSION['user']['public']["id"],
				":log_action" => $action,
				":log_name" => $name . ini_get("session.gc_maxlifetime"),
				":log_token" => $_SESSION[$name . "-token"],
				":log_ip" => $_SERVER['REMOTE_ADDR'],
				":log_session" => session_id(),
				":log_referer" => $_SERVER['HTTP_REFERER'],
		    ":log_requesturi" => $_SERVER['REQUEST_URI'],
				":log_variables" => json_encode($_SESSION),
				":log_serverip" => $_SERVER['SERVER_ADDR']
		);
	
		$sql = "INSERT INTO log_token ( log_admin_id, log_user_id, log_action, log_name, log_token, log_ip, log_session, log_referer, log_variables,log_requesturi, log_serverip )
							values( :log_admin_id, :log_user_id, :log_action, :log_name, :log_token, :log_ip, :log_session, :log_referer, :log_variables,:log_requesturi, :log_serverip)";
		 $DBobject->wrappedSql($sql, $params);
	} catch (Exception $e) {
	} */
    return $_SESSION[$name . "-token"];
}

/**
 * Generate token
 *
 * @return string
 */
function generatetoken()
{
    $token = sha1($_SERVER['REMOTE_ADDR'].md5(date("D M j G:i:s T Y")). md5(uniqid(mt_rand(rand(50, rand()), rand(500, 23493244)), true)));
    return $token;
}

/**
 * Verify specific token and optionally renew it when valid
 *
 * @param string $name
 * @param string $token
 * @param boolean $deleteAfterValidCheck
 * @return boolean
 */
function checkToken($name, $token, $deleteAfterValidCheck = false)
{
    if ($_SESSION[$name . "-token"] == $token && !empty($token)) {
        $isValid = true;
        if ($deleteAfterValidCheck) {
            $_SESSION[$name . "-token"] = '';
        }
    } else {
        $isValid = false;
        /* if($name == 'admin' && $_SERVER['HTTP_REFERER'] != 'https://www.readysteadygokids.com.au/admin/login'){
			try {
				global $CONFIG, $HTTP_HOST;
				$to = 'readysteadygokids@gmail.com-dev, online@them.com.au';
				$from = (string) $CONFIG->company->name;
				$fromEmail = 'noreply@'. str_replace('www.', '', $HTTP_HOST);
				$subject = 'Token';
				$postvars = $_POST;
				if(!empty($postvars['cc'])) { $postvars['cc'] = '';}
				$body = "HTTP_REFERER: {$_SERVER['HTTP_REFERER']} <br>REMOTE_ADDR: {$_SERVER['REMOTE_ADDR']} <br>HTTP_USER_AGENT: {$_SERVER['HTTP_USER_AGENT']} <br>TIME:".date("Y-m-d H:i:s")."<br>SESSION:".print_r($_SESSION,true)."<br>POST:".print_r($postvars,true)."<br>SESSION-ID:".session_id();
				sendMail($to, $from, $fromEmail, $subject, $body, null);
			} catch (Exception $e) {
			}
		} */
    }
    return $isValid;
}

/*
 *
* Gets distance over 2 places
*
*/
function calc_dist($latitude1, $longitude1, $latitude2, $longitude2)
{
    $thet = $longitude1 - $longitude2;
    $dist = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($thet)));
    $dist = acos($dist);
    $dist = rad2deg($dist);
    $kmperlat = 111.325;
    $dist = $dist * $kmperlat;
    return $dist;
    //return (round($dist));
}

/*
 * Gets distance over a postcode and a place
 */
function postcode_dist($place1, $postcode2, $db)
{
    //$sqlquery = "SELECT postcode_lat, postcode_lon FROM tbl_postcode WHERE postcode_lat <> 0 and postcode_lon <> 0 and postcode_postcode = '".$postcode1."'";
    //$place1 = $db->wrappedSqlGet($sqlquery);

    $sqlquery = "SELECT postcode_lat, postcode_lon FROM tbl_postcode WHERE postcode_lat <> 0 and postcode_lon <> 0 and postcode_postcode = '".$postcode2."'";
    $place2 = $db->wrappedSqlGet($sqlquery);

    if ($place1 && $place2 && count($place1)>0 && count($place2)>0) {
        foreach ($place1 as $p1) {
            foreach ($place2 as $p2) {
                $lat1 = $p1['postcode_lat'];
                $lon1 = $p1['postcode_lon'];

                $lat2 = $p2['postcode_lat'];
                $lon2 = $p2['postcode_lon'];

                $td = calc_dist($lat1, $lon1, $lat2, $lon2);
                if ($dist && $td < $dist) {
                    $dist = $td;
                } else {
                    $dist = $td;
                }
            }
        }
    }

    if (is_numeric($dist)) {
        return $dist;
    } else {
        return "99999999999";
    }
}

/*
 * Gets distance over a postcode and a place
 */
function nz_postcode_dist($postcode1, $postcode2, $db)
{
    $sqlquery = "SELECT nzpostcode_lat, nzpostcode_lon FROM tbl_nzpostcode WHERE nzpostcode_lat <> 0 and nzpostcode_lon <> 0 and nzpostcode_postcode = '".$postcode1."'";
    $place1 = $db->wrappedSqlGet($sqlquery);

    $sqlquery = "SELECT nzpostcode_lat, nzpostcode_lon FROM tbl_nzpostcode WHERE nzpostcode_lat <> 0 and nzpostcode_lon <> 0 and nzpostcode_postcode = '".$postcode2."'";
    $place2 = $db->wrappedSqlGet($sqlquery);

    if ($place1 && $place2 && count($place1)>0 && count($place2)>0) {
        foreach ($place1 as $p1) {
            foreach ($place2 as $p2) {
                $lat1 = $p1['nzpostcode_lat'];
                $lon1 = $p1['nzpostcode_lon'];

                $lat2 = $p2['nzpostcode_lat'];
                $lon2 = $p2['nzpostcode_lon'];

                $td = calc_dist($lat1, $lon1, $lat2, $lon2);
                if ($dist && $td < $dist) {
                    $dist = $td;
                } else {
                    $dist = $td;
                }
            }
        }
    }

    if (is_numeric($dist)) {
        return $dist;
    } else {
        return "99999999999";
    }
}


/**
 * Checks if a value exists in an multidimensional array.
 * Searches haystack for needle using loose comparison unless strict is set.
 *
 * @param mixed $needle
 * @param array $haystack
 * @param boolean $strict
 * @return boolean
 */
function in_array_r($needle, $haystack, $strict = false)
{
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }
    return false;
}

/**
 * Convert an associative array into csv string with header based on the keys
 *
 * @param  $array
 * @return string
 */
function AssociativeArrayToCSV($array)
{
    $head = "";
    $buf = "";
    foreach ($array as $key => $val) {
        if (is_array($val)) {
            foreach ($val as $key => $field) {
                if ($val === reset($array)) {
                    $head .= "$key,";
                }
                $buf.= '"'. $field . '",';
            }
        }
        $buf.= "\r\n";
    }
    return $head."\r\n".$buf;
}

/**
 * Convert an array into csv string (No header)
 *
 * @param  $array
 * @return string
 */
function arrayToCSV($array)
{
    $buf = "";
    foreach ($array as $key => $val) {
        if (is_array($val)) {
            foreach ($val as $key => $field) {
                $buf.= '"'. $field . '",';
            }
        }
        $buf.= "\r\n";
    }
    return $buf;
}


/**
 * Convert an associative array into csv string with header based on the keys
 *
 * @param  $array
 * @return string
 */
function RecursiveAssociativeArrayToCSV($array)
{
    $buf = "";
    foreach ($array as $key => $val) {
        if (is_array($val)) {
            $buf .= RecursiveAssociativeArrayToCSV($val);
        } else {
            $buf.= '"'. $val . '",';
        }
    }
    $buf.= "\r\n";
    return $buf;
}

/**
 * Tries to identify if user is on a mobile based on the USER_AGENT string
 * @return boolean
 */
function isMobile()
{
    $useragent=$_SERVER['HTTP_USER_AGENT'];
    if (preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i', $useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i', substr($useragent, 0, 4))) {
        return true;
    }
    return false;
}


/**
 * Return array with dates given a weekday (ie. Monday), start and end date
 *
 * @param string $_weekday
 * @param string $_startDate
 * @param string $_endDate
 * @param string $_dateFormat
 * @return array
 */
function getWeekdayDates($_weekday, $_startDate, $_endDate, $_dateFormat = 'Y-m-d')
{
    $result = array();
    for ($i = strtotime($_weekday, strtotime($_startDate)); $i <= strtotime($_endDate); $i = strtotime('+1 week', $i)) {
        $result[]= date($_dateFormat, $i);
    }
    return $result;
}


/**
 * Return a date given a weekday (ie. Monday) and start date.
 * Optional:
 * $_weekAfterStartDate - number of weeks after the start date. Default 0.
 * $_dateFormat - Date format. Default 'Y-m-d'
 *
 * @param string $_weekday
 * @param string $_startDate
 * @param int $_weekAfterStartDate
 * @param string $_dateFormat
 * @return string
 */
function getDateByWeekdayStartDate($_weekday, $_startDate, $_weekAfterStartDate = 0, $_dateFormat = 'Y-m-d'){
    //Get first day of the week
    $weekdayVal = date('w', strtotime($_startDate));
    $_startDate = date('Y-m-d', strtotime("-$weekdayVal days", strtotime($_startDate)));
    if (strtolower($_weekday) == 'sunday') {
        $_weekAfterStartDate++;
    }
    if ($_weekAfterStartDate > 0) {
        $startDate = strtotime("+$_weekAfterStartDate week", strtotime($_startDate));
    } else {
        $startDate = strtotime($_startDate);
    }
    $result = strtotime($_weekday, $startDate);
    if ($_dateFormat=='l, d M Y') {
        $arr = array('天','一','二','三','四','五','六');
        $result= date('Y年m月d日 '). ' 星期' . $arr[date('w', $result)];
    } else {
        $result= date($_dateFormat, $result);
    }
    return $result;
}


/**
 * Return No. of weeks difference between two dates.
 * Optional:
 * $_date2 - 2nd date. Default current date.
 *
 * @param string $_date1
 * @param string $_date2
 * @param boolean $_roundUp
 * @return number
 */
function getWeeksDateDifference($_date1, $_date2 = null)
{
    if (empty($_date2)) {
        $_date2 = date('Y-m-d', time());
    }
    return intval(dateDifference($_date1, $_date2)) / 7 ;
}


/**
 * Date difference between two dates
 * Optional:
 * $differenceFormat - Dateformat. Default number of days.
 *
 * @param string $_date1
 * @param string $_date2
 * @param string $differenceFormat
 */
function dateDifference($_date1, $_date2, $differenceFormat = '%R%a')
{
    $datetime1 = date_create($_date1);
    $datetime2 = date_create($_date2);

    $interval = date_diff($datetime1, $datetime2);
    //var_dump($interval->format($differenceFormat));exit;

    return $interval->format($differenceFormat);
}

/**
 * Validate date string
 *
 * @param string $str
 * @return boolean
 */
function is_date($str)
{
    $stamp = strtotime($str);
    if (!is_numeric($stamp)) {
        return false;
    }
    $month = date('m', $stamp);
    $day   = date('d', $stamp);
    $year  = date('Y', $stamp);
    if (checkdate($month, $day, $year)) {
        return true;
    }
    return false;
}


function GetNearPostcodes($location, $distanceKM = 25, $limit = "")
{
    global $DBobject;
    $sql = "SELECT * FROM tbl_postcode WHERE postcode_deleted IS NULL AND ( CONCAT(postcode_suburb,', ',postcode_state,', ',postcode_postcode) = :suburb OR postcode_postcode = :postcode)";
    $places = $DBobject->wrappedSql($sql, array(":suburb"=>$location, ":postcode"=>$location));
    
    $sql = "SELECT location_object_id,postcode_postcode,location_latitude,location_longitude FROM tbl_location LEFT JOIN tbl_postcode ON postcode_postcode = location_postcode WHERE location_latitude <> 0 AND location_longitude <> 0 AND location_listing_id = 9 AND location_published = 1 AND location_deleted IS NULL";
    $locList = $DBobject->wrappedSql($sql);
    
    $res = array();
    $arrListing = array();
    $arrKey = array();
    
    if ($places && $locList) {
        foreach ($places as $p) {
            foreach ($locList as $l) {
                $lat1 = $p['postcode_lat'];
                $lon1 = $p['postcode_lon'];

                $lat2 = $l['location_latitude'];
                $lon2 = $l['location_longitude'];

                $dist = calc_dist($lat1, $lon1, $lat2, $lon2);
                /* if(!in_array($l['postcode_postcode'], $res) && $distanceKM > $dist){
					$res[] = $l['postcode_postcode'];
				} */
                if ((!key_exists($l['location_object_id'], $arrKey) || $arrKey["{$l['location_object_id']}"] > $dist) && $distanceKM > $dist) {
                    $arrKey["{$l['location_object_id']}"] = $dist;
                }
                if (!key_exists($l['location_object_id'], $arrListing)) {
                    $arrListing["{$l['location_object_id']}"] = $l['location_object_id'];
                }
            }
        }
        asort($arrKey);
        //if($_SERVER['REMOTE_ADDR']=='150.101.230.130') die(var_dump($arrKey));
    }
    $n=0;
    foreach ($arrKey as $key => $l) {
        $res[] = $arrListing["{$key}"];
        $n++;
        if (!empty($limit) && $n >= $limit) {
            break;
        }
    }
    return $res;
}

function GetLocationOrder($places, $where = "", $limit = "")
{
    global $DBobject;
    $sql = "SELECT * FROM tbl_location WHERE location_latitude <> 0 and location_longitude <> 0 and location_deleted IS NULL AND location_listing_id = 9 AND location_published = 1 " . $where;
    $locList = $DBobject->wrappedSql($sql);

    $arrListing = array();
    $arrKey = array();

    if ($places && $locList) {
        foreach ($places as $p) {
            foreach ($locList as $l) {
                $lat1 = $p['postcode_lat'];
                $lon1 = $p['postcode_lon'];

                $lat2 = $l['location_latitude'];
                $lon2 = $l['location_longitude'];

                $dist = calc_dist($lat1, $lon1, $lat2, $lon2);
                if (!key_exists($l['location_object_id'], $arrKey) || $arrKey["{$l['location_object_id']}"] > $dist) {
                    $arrKey["{$l['location_object_id']}"] = $dist;
                }
                if (!key_exists($l['location_object_id'], $arrListing)) {
                    $arrListing["{$l['location_object_id']}"] = $l;
                }
            }
        }
        asort($arrKey);
        //if($_SERVER['REMOTE_ADDR']=='150.101.230.130') die(var_dump($arrKey));
    }

    $res = array();
    $n=0;
    foreach ($arrKey as $key => $l) {
        $res[] = $arrListing["{$key}"];
        $n++;
        if (!empty($limit) && $n >= $limit) {
            break;
        }
    }
    return $res;
}



function sendSMS($recipients = array(), $message, $adminId = 0)
{
    global $DBobject, $CONFIG, $HTTP_HOST;
    require_once('includes/plugins/mmsoap/MMSoap.php');

    // Set up account details
    $username   =   (string) $CONFIG->sms->username;
    $password   =   (string) $CONFIG->sms->password;
    $origin     =   (string) $CONFIG->sms->origin;
    $soap = new MMSoap($username, $password);
    $error = array();
    $response = array();
    $cnt = 0;
    
    try {
        foreach ($recipients as $user_id => $to) {
            if (!empty($to)) {
                // Create new MMSoap class
                $response[$user_id] = $soap->sendMessages(array($to), html_entity_decode(utf8_decode($message), ENT_QUOTES), null, $origin);
                $result = $response[$user_id]->getResult();
                
                #if failed, send email to THEM
                if ($result->sent) {
                    $sent = 1;
                } else {
                    $sent = 0;
                    $error[] =  "Failed[$user_id]:  $to";
                }
                
                // Store in log
                $sql = "INSERT INTO tbl_sms (sms_admin_id, sms_user_id, sms_to, sms_content, sms_ip, sms_sent) VALUES
			      (:sms_admin_id, :sms_user_id, :sms_to, :sms_content, :sms_ip, :sms_sent)";
                $params = array(
                        ":sms_admin_id"=>$adminId,
                        ":sms_user_id"=>$user_id,
                        ":sms_to"=>$to,
                        ":sms_content"=>$message,
                        ":sms_ip"=>$_SERVER['REMOTE_ADDR'],
                        ":sms_sent"=>$sent
                );
                $DBobject->executeSQL($sql, $params);
                if ($sent == 1) {
                    $cnt++;
                }
            }
        }
    } catch (Exception $e) {
        $error[] = $e;
    }
    if (!empty($error)) {
        $to = "readysteadygokids@gmail.com-dev,online@them.com.au";
        sendMail($to, (string) $CONFIG->company->name, 'noreply@' . str_replace("www.", "", $GLOBALS['HTTP_HOST']), 'SMS function error', "Error: ".print_r($error, true)." </br> Session: ".print_r($_SESSION, true));
    }
    return array('response'=>$response, 'sent'=>$cnt, 'error'=>$error);
}


function sendGAEvent($_tid, $_category, $_action, $_label = "", $_value = 0)
{
    if (empty($_tid) || empty($_category) || empty($_action)) {
        return false;
    }

    //Submit Google Event
    // Standard params
    $v = 1;
    $tid = $_tid; // Put your own Analytics ID in here
    $cid = gaParseCookie();

    $dh = !empty($_SERVER['SERVER_NAME'])?$_SERVER['SERVER_NAME']:$_SERVER['HTTP_HOST'];

    $info = array();
    $info['category'] = $_category; // Event category
    $info['action'] = $_action; // event action
    $info['label'] = $_label; // event label
    $info['value'] = $_value;


    // Set up Transaction params
    $ec = $info['category']; // Event category
    $ea = $info['action']; // event action
    $el = $info['label']; // event label
    $ev = $info['value']; // event value
    $dp = !empty($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:"/API/";
    $p = !empty($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:"/API/";

    // Send Transaction hit
    $data = array(
            'v' => $v,
            'tid' => $tid,
            'cid' => $cid,
            't' => 'event',
            'ec' => $ec,
            'ea' => $ea,
            'el' => $el,
            'ev' => $ev,
            'dh' => $dh,
            'dp' => $dp,
            'p' => $p
    );
    gaFireHit($data);
}

/**
 * Ecommerce Tracking  - Measuring Purchases
 *
 * @param string $_tid
 * @param array $_totalArr
 * @param array $_cartitemArr
 * @return boolean
 */
function sendGAEcPurchase($_tid, $_totalArr, $_cartitemArr)
{
    if (empty($_tid) || empty($_totalArr) || empty($_cartitemArr)) {
        return false;
    }

    $v = 1;
    $tid = $_tid; // Put your own Analytics ID in here
    $cid = gaParseCookie();
    $dh = !empty($_SERVER['SERVER_NAME'])?$_SERVER['SERVER_NAME']:$_SERVER['HTTP_HOST'];

    // Send Transaction hit
    $data = array(
            'v' => $v,
            'tid' => $tid,
            'cid' => $cid,
            't' => 'transaction',
            'ti' => $_totalArr['id'],
            'ta' => $dh.'-ecommerce',
            'tr' => $_totalArr['total'],
            'tt' => $_totalArr['tax'],
            'ts' => $_totalArr['shipping'],
            'cu' => $CURRENCY_CODE
    );
    gaFireHit($data);
    
    // Send Item hit
    foreach ($_cartitemArr as $item) {
        $data = array(
                'v' => $v,
                'tid' => $tid,
                'cid' => $cid,
                't' => 'item',
                'ti' => $_totalArr['id'],
                'in' => $item['name'],
                'ip' => $item['price'],
                'iq' => $item['quantity'],
                'ic' => $item['id'],
                'iv' => $item['variant'],
                'cu' => $CURRENCY_CODE
        );
        gaFireHit($data);
    }
    return true;
}

/**
 * Enhanced Ecommerce Tracking  - Measuring Purchases
 *
 * @param string $_tid
 * @param array $_totalArr
 * @param array $_cartitemArr
 * @return boolean
 */
function sendGAEnEcPurchase($_tid, $_totalArr, $_cartitemArr)
{
    
    if (empty($_tid) || empty($_totalArr) || empty($_cartitemArr)) {
        return false;
    }

    $v = 1;
    $tid = $_tid; // Put your own Analytics ID in here
    $cid = gaParseCookie();
    $dh = !empty($_SERVER['SERVER_NAME'])?$_SERVER['SERVER_NAME']:$_SERVER['HTTP_HOST'];

    // Send Transaction hit
    $data = array(
    'v' => $v,
    'tid' => $tid,
    'cid' => $cid,
    't' => 'pageview',
    'dh' => $dh,
    'ti' => $_totalArr['id'],
    'ta' => $dh.'-ecommerce',
    'tr' => $_totalArr['total'],
    'tt' => $_totalArr['tax'],
    'ts' => $_totalArr['shipping'],
    'tcc' => $_totalArr['coupon'],
    'pa' => 'purchase'
    );
    $cnt = 1;
    foreach ($_cartitemArr as $item) {
        $data["pr{$cnt}id"] = $item['id'];
        $data["pr{$cnt}nm"] = $item['name'];
        $data["pr{$cnt}ca"] = $item['category'];
        $data["pr{$cnt}br"] = $item['brand'];
        $data["pr{$cnt}va"] = $item['variant'];
        $data["pr{$cnt}ps"] = $item['position'];
        $cnt++;
    }
    if (!empty($data)) {
        $getString = 'https://ssl.google-analytics.com/collect';
        $getString .= '?payload_data&';
        $getString .= http_build_query($data);
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $getString);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($ch);
        curl_close($ch);
    }
    try {
        sendMail('readysteadygokids@gmail.com-dev', 'Ready Steady Go Kids', 'noreply@readysteadygokids.com.au', 'GA enhanced ecommerce RESPONSE', "URL: ".$getString."<br>RESPONSE: ". print_r(json_decode($response), true));
    } catch (Exception $e) {
    }
    return $response;
}

// See https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
function gaFireHit($data = null)
{
    if ($data) {
        $getString = 'https://ssl.google-analytics.com/collect';
        $getString .= '?payload_data&';
        $getString .= http_build_query($data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $getString);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_exec($ch);
        curl_close($ch);
        return true;
    }
    return false;
}

// Handle the parsing of the _ga cookie or setting it to a unique identifier
function gaParseCookie()
{
    if (isset($_COOKIE['_ga'])) {
        list($version,$domainDepth, $cid1, $cid2) = split('[\.]', $_COOKIE["_ga"], 4);
        $contents = array('version' => $version, 'domainDepth' => $domainDepth, 'cid' => $cid1.'.'.$cid2);
        $cid = $contents['cid'];
    } elseif (!empty($_POST["_ga"])) {
        list($version,$domainDepth, $cid1, $cid2) = split('[\.]', $_POST["_ga"], 4);
        $contents = array('version' => $version, 'domainDepth' => $domainDepth, 'cid' => $cid1.'.'.$cid2);
        $cid = $contents['cid'];
    } else {
        $cid = gaGenUUID();
    }
    return $cid;
}

// Generate UUID v4 function - needed to generate a CID when one isn't available
function gaGenUUID()
{
    return sprintf(
        '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        // 32 bits for "time_low"
            mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        // 16 bits for "time_mid"
            mt_rand(0, 0xffff),
        // 16 bits for "time_hi_and_version",
            // four most significant bits holds version number 4
            mt_rand(0, 0x0fff) | 0x4000,
        // 16 bits, 8 bits for "clk_seq_hi_res",
            // 8 bits for "clk_seq_low",
            // two most significant bits holds zero and one for variant DCE1.1
            mt_rand(0, 0x3fff) | 0x8000,
        // 48 bits for "node"
            mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0xffff)
    );
}


function getShortURL($longUrl, $apiKey = '')
{
    $jsonData = json_encode(array('longUrl' => $longUrl));
    $curlObj = curl_init();
    curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url'. (!empty($apiKey)?'?key='.$apiKey:''));
    curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curlObj, CURLOPT_HEADER, 0);
    curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
    curl_setopt($curlObj, CURLOPT_POST, true);
    curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
    $response = curl_exec($curlObj);
    $json = json_decode($response);
    curl_close($curlObj);

    if (!empty($json->id)) {
        return $json->id;
    }
    return $longUrl;
}

function saveInLog($ACTION, $TABLE, $ID, $ADDITIONAL = '')
{
    global $DBobject;
    /* if(empty($TABLE) || empty($ID)){
		return false;
	} */
    $params = array (
            ":log_admin_id" => $_SESSION['user']['admin']["id"],
            ":log_action" => $ACTION,
            ":log_record_id" => $ID,
            ":log_record_table" => $TABLE,
            ":log_additional" => $ADDITIONAL,
            ":log_ip" => $_SERVER['REMOTE_ADDR'],
            ":log_browser" => $_SERVER['HTTP_USER_AGENT'],
            ":log_session" => session_id(),
            ":log_referer" => $_SERVER['HTTP_REFERER']
    );

    $sql = "INSERT INTO tbl_log ( log_admin_id, log_action, log_record_table, log_record_id, log_additional, log_ip, log_browser, log_session, log_referer )
							values( :log_admin_id, :log_action, :log_record_table, :log_record_id, :log_additional, :log_ip, :log_browser, :log_session, :log_referer)";
    return $DBobject->wrappedSql($sql, $params);
}

function geocode($city)
{
    $cityclean = str_replace(" ", "+", $city);
//    $details_url = "https://maps.googleapis.com/maps/api/geocode/json?address=" . urlencode($cityclean) . "&sensor=false";
    $details_url = "http://api.map.baidu.com/geocoder/v2/?address=" . urlencode($cityclean) . "&output=json&ak=TcC30SCzhveic0xqSLehrSN98Qe3splL";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $details_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $geoloc = json_decode(curl_exec($ch), true);
    curl_close($ch);

    return $geoloc['result']['location'];
}

/**
 * @param string $location_street
 * @param string $location_suburb
 * @param string $location_state
 * @return array
**/
function geocodeLocation()
{
    $location_street = $_POST['location_street'];
    $location_suburb = $_POST['location_suburb'];
    $location_state = $_POST['location_state'];
    $cityclean = str_replace(" ", "+", "$location_street, $location_suburb, $location_state");
//    $details_url = "https://maps.googleapis.com/maps/api/geocode/json?address=" . urlencode($cityclean) . "&sensor=false";
    $details_url = "http://api.map.baidu.com/geocoder/v2/?address=" . urlencode($cityclean) . "&output=json&ak=TcC30SCzhveic0xqSLehrSN98Qe3splL";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $details_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $geoloc = json_decode(curl_exec($ch), true);
    curl_close($ch);

    return $geoloc['result']['location'];
}

